package com.tanhua.server.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.tanhua.dubbo.server.api.SubmitQuestionnaireApi;
import com.tanhua.pojo.Answers;
import com.tanhua.pojo.Report;
import com.tanhua.utils.UserThreadLocal;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SubmitQuestionnaireService {

    @Reference(version = "1.0.0")
    private SubmitQuestionnaireApi submitQuestionnaireApi;

    public String getResult(Map<String, Object> param) {

            Long userId = UserThreadLocal.get().getId();

            Object answers = param.get("answers");

            String jsonString = JSON.toJSONString(answers);

            List<Answers> answersList = JSONArray.parseArray(jsonString, Answers.class);

            Integer star = 0;

            int count = answersList.size();

            if (count == 10){

                int total_score = 0;

                Answers answers1 = answersList.get(0);

                star = submitQuestionnaireApi.selectQuestionStar(Integer.valueOf(answers1.getQuestionId()));


                for (Answers answers2 : answersList) {
                    Integer score = submitQuestionnaireApi.slelctScore(answers2.getQuestionId(), answers2.getOptionId());

                    total_score = total_score + score;
                }

                System.out.println(total_score);

                Report report = new Report();

                report.setUserId(userId);
                report.setTotalScore(total_score);
                report.setCreateTime(new Date());
                report.setStar(star);

                submitQuestionnaireApi.insertQuestionnaire(report);

                Integer reportId = submitQuestionnaireApi.getReportId(report.getUserId().intValue(),report.getStar());

                System.out.println(reportId);

                return reportId.toString();
            }

            return null;
    }
}
